package com.cg.controller;

import com.cg.dto.LoginDTO;
import com.cg.dto.RegisterDTO;
import com.cg.common.Result;
import com.cg.dto.UserDTO;
import com.cg.service.UserService;
import com.cg.utils.JwtUtil;
import com.cg.common.BaseContext;
import com.cg.constant.JwtClaimsConstant;
import com.cg.constant.MessageConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户认证控制器
 */
@RestController
@RequestMapping
@Slf4j
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody @Validated LoginDTO loginDTO) {
        try {
            // 用户名密码登录
            UserDTO user = userService.login(loginDTO.getUsername(), loginDTO.getPassword());
            
            if (user != null) {
                // 生成JWT Token
                Map<String, Object> claims = new HashMap<>();
                claims.put(JwtClaimsConstant.USER_ID, user.getId());
                claims.put(JwtClaimsConstant.USERNAME, user.getUsername());
                claims.put("email", user.getEmail());
                String token = JwtUtil.genToken(claims);
                
                log.info("用户登录成功: {}", user.getUsername());
                return Result.success(token, "登录成功");
            } else {
                return Result.error(MessageConstant.LOGIN_FAILED);
            }
        } catch (Exception e) {
            log.error("登录异常: {}", e.getMessage(), e);
            return Result.error(MessageConstant.LOGIN_FAILED);
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody @Validated RegisterDTO registerDTO) {
        try {
            log.info("接收到注册请求：{}", registerDTO);
            
            // 参数验证
            if (registerDTO == null) {
                return Result.error("注册信息不能为空");
            }
            
            if (registerDTO.getPassword() == null || registerDTO.getPassword().isEmpty()) {
                return Result.error("密码不能为空");
            }
            
            if (registerDTO.getConfirmPassword() == null || registerDTO.getConfirmPassword().isEmpty()) {
                return Result.error("确认密码不能为空");
            }
            
            if (!registerDTO.getPassword().equals(registerDTO.getConfirmPassword())) {
                return Result.error("两次输入的密码不一致");
            }
            
            if (registerDTO.getProvinceCode() == null || registerDTO.getProvinceCode().isEmpty()) {
                return Result.error("请选择省份");
            }
            
            if (registerDTO.getIdealKeywords() == null || registerDTO.getIdealKeywords().isEmpty()) {
                return Result.error("请至少选择一个理想岗位关键词");
            }
            
            // 执行注册
            userService.register(registerDTO);
            
            log.info("用户注册成功");
            return Result.success("注册成功");
            
        } catch (Exception e) {
            log.error("注册异常: {}", e.getMessage(), e);
            return Result.error("注册失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/userInfo")
    public Result<UserDTO> getUserInfo() {
        // 这个接口需要登录，会被拦截器处理
        // 可以从BaseContext获取当前用户ID
        try {
            Long userId = BaseContext.getCurrentId();
            if (userId == null) {
                return Result.error("用户未登录");
            }

            UserDTO user = userService.getUserById(userId);
            if (user != null) {
                return Result.success(user, "获取用户信息成功");
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            log.error("获取用户信息异常: {}", e.getMessage(), e);
            return Result.error("获取用户信息失败");
        }
    }
}

